﻿using Microsoft.EntityFrameworkCore;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace LCS.Domain.UOW
{
    /// <summary>
    /// 工作单元模式
    /// </summary>
    /// <typeparam name="TDbContext"></typeparam>
    public class UnitOfWork<TDbContext> : IUnitOfWork where TDbContext : DbContext
    {

        /// <summary>
        /// dbContext上下文
        /// </summary>
        private readonly TDbContext _dbContext;
        /// <summary>
        /// 构造函数
        /// </summary>
        /// <param name="dbContext"></param>
        public UnitOfWork(TDbContext dbContext)
        {
            _dbContext = dbContext;
        }


        public async Task<int> SaveChangesAsync()
        {
            int code;
            try
            {
                code = await _dbContext.SaveChangesAsync();
            }
            catch (DbUpdateException e)
            {
                throw new Exception(e.InnerException == null ? e.Message : e.InnerException.Message);
            }
            return code;
        }




        private bool disposed = false;

        protected virtual void Dispose(bool disposing)
        {
            if (!this.disposed)
            {
                if (disposing)
                {
                    _dbContext.Dispose();
                }
            }
            this.disposed = true;
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }

    }
}
